// pages/rent/submit.js

const app = getApp();
Page({
  data: {
    bgTextStyle: 'dark',
    scrollTop: '200rpx',
    bgColor: '#ff0000',
    bgColorTop: '#00ff00',
    bgColorBottom: '#0000ff',
    nbTitle: '公寓预约',
    nbLoading: false,
    nbFrontColor: '#000000',
    nbBackgroundColor: '#ffffff',
    pageStyle: "color:#333333;background-color: #f1f1f1;",
    binds: [],
    array: [],
    images: [{url:''}, {url:''}],
    index: 0,
    positions:[],
    position: 0,
    
    isAnother: false,
    start: "2022-02-02",
    date: "2022-02-02",
    time: "09:00",
    order_id: 0,
    
    type: 0,
    title: "",
    code: "",
    addreess: "",
    tel: "",
    bank: "",
    bank_code: "",
    email: "",
    orderList:[],
    hasChange: false,
    enableRequest: true,
    text: '',
    info: {},
    typeId: 1,
    types: [ {name: "按天计", value: 0}, {name: "按月计", value: 1},],
    numId: 0,
    numbers: [
      {name: "1人", value: 1},
      {name: "2人", value: 2},
      {name: "3人", value: 3},
      {name: "4人", value: 4},
      {name: "5人", value: 5},
    ],
    startDate: "",
    endDate: "",
    num: 0,
    minDate: "2022-10-10",
    maxDate: "2099-12-30",
    comeDate: "",
    CheckInDate: "",
    name: "",
    phone: "",
    reason: "",
    post: "",
    cname: "",
    cphone: "",
    idcard: "",
    remark: "",
    ready: false
  },
  onLoad: function (options) {
  },
  onReady: function () {
    let v = this;
    const info = app.globalData.info;
    const newData = {};
    // newData.images = [{img: info.room_img}];
    newData.info = info;
    if (info.type === 0) {
      newData.typeId = 0;
    }
    console.log("onReady info", info);
    v.setData(newData);
  },
  onShow: function () {
    let v = this;
    let data = {};
    let dt = new Date();
    let hh = dt.getHours() + 1;
    let hhs= hh > 9 ? ('' + hh) : ('0' + hh);
    let today = app.ymd();
    let nxday = app.ymd(dt.getTime() + 1000 * 60 * 60 *24);
    data.minDate   = today;
    data.startDate = today;
    data.endDate   = nxday;
    console.log("onShow",data);
    v.setData(data);
  },
  getMyBinds: function() {
    let v = this;
    let token = app.globalData.token;
    
  },
  bindNumChange(ev){
    const idx = parseInt(ev.detail.value) || 0;
    console.log("bindNumChange", idx);
    this.setData({numId: idx});
  },
  bindStartDateChange(ev){
    this.setData({startDate: (ev.detail.value) || 0});
  },
  bindEndDateChange(ev){
    this.setData({endDate: (ev.detail.value) || 0});
  },
  bindComeDateChange(ev) {
    this.setData({comeDate: (ev.detail.value) || 0});
  },
  bindCheckInDateChange(ev) {
    this.setData({CheckInDate: (ev.detail.value) || 0});
  },
  bindKeyInputNum(ev){
    let val = ev.detail.value;
    console.log("bindKeyInputNum",val);
    this.setData({num: val});
  },
  bindKeyInputName(ev){
    let val = ev.detail.value;
    console.log("bindKeyInputName",val);
    this.setData({name: val});
  },
  bindKeyInputPhone(ev){
    let val = ev.detail.value;
    console.log("bindKeyInputPhone",val);
    this.setData({phone: val});
  },
  bindKeyInputReason(ev){
    let val = ev.detail.value;
    console.log("bindKeyInputReason",val);
    this.setData({reason: val});
  },
  bindKeyInputPost(ev){
    let val = ev.detail.value;
    console.log("bindKeyInputPost",val);
    this.setData({post: val});
  },
  bindKeyInputCname(ev){
    let val = ev.detail.value;
    console.log("bindKeyInputCname",val);
    this.setData({cname: val});
  },
  bindKeyInputCphone(ev){
    let val = ev.detail.value;
    console.log("bindKeyInputCphone",val);
    this.setData({cphone: val});
  },
  bindKeyInputRemark(ev){
    let val = ev.detail.value;
    console.log("bindKeyInputRemark",val);
    this.setData({remark: val});
  },
  bindKeyInputIdcard(ev){
    let val = ev.detail.value;
    console.log("bindKeyInputIdcard",val);
    this.setData({idcard: val});
  },
  doRequestRent(ev){
    let v = this;
    console.log("doRequestRent");
    let url = app.globalData.host + '/api/rent/add';
    let data = {token: app.globalData.token};
    if(!v.data.name || !v.data.phone || !v.data.idcard) {
      wx.showToast({ title: '请完善租户信息' ,icon:'none'});
      return;
    }

    let len = v.data.idcard.length;
    if(len != 18) {
      wx.showToast({ title: '身份证信息有误' ,icon:'none'});
      return;
    }

    let imgs = [];
    for(let k in v.data.images) if (v.data.images[k].url) imgs.push(v.data.images[k].url);
    // room_id
    let num = 0;
    data.room_id   = v.data.info.room_id;
    data.username  = v.data.name;
    data.phone     = v.data.phone;
    data.idcard    = v.data.idcard;
    data.cert      = imgs.toString();
    // data.remark    = v.data.remark;
    data.start_time= v.data.startDate;
    data.end_time  = v.data.endDate;
    data.num       = v.data.num;
    data.number    = v.data.numId + 1;
    data.come_time = v.data.comeDate;
    data.come_addr_time    = v.data.CheckInDate;
    data.come_reason       = v.data.reason;
    data.company   = v.data.post;
    data.contact_username  = v.data.cname;
    data.contact_phone  = v.data.cphone;
    
    wx.request({
      url: url, data: data,
      success (res) {
        let r = res.data;
        if(r.code == 200 && r.data) {
          console.log("doRequestRent", r);
          wx.showToast({ title: r.msg || '申请成功',icon:'none'})
          v.setData({enableRequest: false});
          const rent_id = r.data.rent_id;
          if (parseInt(rent_id) == rent_id) {
            app.globalData.orderInfo = r.data;
            wx.navigateTo({url: '/pages/rent/orderInfo'});
          } else {
            wx.navigateTo({url: '/pages/rent/order'});
          }
        } else {
          wx.showToast({ title: r.msg || '申请失败',icon:'none'})
        }
      }
    })
  },
  addAvator(){
    let v = this;
    let images = v.data.images;
    let item = {url: ''};
    if (images.length > 2) {
      wx.showToast({ title: '最多添加三张图片', icon: 'none' });
      return;
    }
    images.push(item);
    v.setData({images:images});
  },
  uploadAvator(ev) {
    const v = this;
    console.log("uploadAvator",ev);
    let index = 0;
    let ds = ev.target.dataset;
    if (ds) index = parseInt(ds.index) || 0;
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      sizeType: ['compressed'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        const size = res.tempFiles[0].size;
        const name = v.getRandFileName(tempFilePath);
        console.log(name,res);
        const url = app.globalData.host + "/api/common/upimg";
        wx.uploadFile({
          url: url, //仅为示例，非真实的接口地址
          filePath: tempFilePath,
          name: 'file',
          formData: {'user': v.data.uid },
          success (res){
            let data = res.data
            if(typeof data == 'string') data = JSON.parse(data);
            console.log(data,res);
            let images = v.data.images;
            if (data.code == 200) {
              let src = data.data.src;
              images[index].url = src;
              v.setData({images: images});
            } else {
              if (data.msg) wx.showToast({ title: data.msg, icon: 'none' });
            }
          },
          fail (err) {
            console.log("fail", err);
          }
        })
      }
    })
  },
  getRandFileName(filePath) {
    let v = this;
    const extIndex = filePath.lastIndexOf('.');
    const extName = extIndex === -1 ? '' : filePath.substr(extIndex);
    let rname = parseInt(`${Date.now()}${Math.floor(Math.random() * 900 + 100)}`, 10).toString(36);
    let saveName = rname + extName;
    if(v.data.uid) {
      saveName = "" + v.data.uid + extName;
    }
    return saveName;
  },

  onSuccess: function (res) {
    console.log(res.detail);
  },
  onFail: function (res) {
    console.log(res);
  },
  onHide: function () {
  },
  onUnload: function () {
  },
  onPullDownRefresh: function () {
  },
  onReachBottom: function () {
  },
  onShareAppMessage: function () {
  }
})